package com.digitalchina.lxnsy.activity.old;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessRealTimePrice;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.RealTimeListVO;
import com.digitalchina.lxnsy.toolkit.DateStyle;
import com.digitalchina.lxnsy.toolkit.DateUtil;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.viewholder.RealTimePriceDataDetailsHolder;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：白彦东
 * 创建时间：2017/3/20 16:57
 * 修改备注：
 * ================================================
 */

public class RealTimePriceDataDetailsActivity extends BaseActivity implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    @Bind(R.id.data_detail_tv_pic_data)
    TextView dataDetailTvPicData;
    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;
    @Bind(R.id.layout_real_time_price_tv_week)
    TextView layoutRealTimePriceTvWeek;
    @Bind(R.id.layout_real_time_price_tv_month)
    TextView layoutRealTimePriceTvMonth;
    @Bind(R.id.layout_real_time_price_tv_custom)
    TextView layoutRealTimePriceTvCustom;

    private RecyclerArrayAdapter adapter;
    private int page = 1;
    private int limit = 20;
    private List<RealTimeListVO> realTimeListVOList = new ArrayList<>();

    private String priceId;
    private String title;
    private String type = "0";
    private TimePickerView pvStartTime; // 自定义开始日期
    private TimePickerView pvEndTime; // 自定义结束日期
    private String mStartDate = "", mEndDate = ""; // 自定义开始结束时间
    private String standard = "";
    private String packing = "";
    private String storageMode = "";

    //    private RealPriceDetailsVO realPriceDetailsVO;
    private Map<String, String> maps = new HashMap<>();

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_real_time_price_data_details);
    }

    @Override
    public void initMember() {
        if (getIntent().hasExtra("map")) {
            maps = (Map<String, String>) getIntent().getSerializableExtra("map");
//            priceId = realPriceDetailsVO.getId();
//            standard = null == realPriceDetailsVO.getFarmProductStandard() ? "" : realPriceDetailsVO.getFarmProductStandard().getCode();
//            packing = null == realPriceDetailsVO.getFarmProductPacking() ? "" : realPriceDetailsVO.getFarmProductPacking().getCode();
//            storageMode = null == realPriceDetailsVO.getFarmProductStorageMode() ? "" : realPriceDetailsVO.getFarmProductStorageMode().getStorageModeName();
            priceId = maps.get("priceId");
            title = maps.get("title");
            standard = maps.get("standardCode");
            packing = maps.get("packingCode");
            storageMode = maps.get("storageCode");

            setTitle(title);
            onRefresh();
        }
        initRecyclerView();
        initStartTimePicker();
        initEndTimePicker();
        setWeekSelected();
    }

    private void initRecyclerView() {


        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        recyclerView.addItemDecoration(Utils.setSpaceDecoration(this, false, false, false));

        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new RealTimePriceDataDetailsHolder(parent);
            }
        });

    }

    @Override
    public void addListener() {
        recyclerView.setRefreshListener(this);

        adapter.setMore(R.layout.view_more, this);

        adapter.setNoMore(R.layout.view_nomore);

        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });

        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                //TODO ITEM 点击事件
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (recyclerView == null) {
                    return;
                }
                if (recyclerView.getSwipeToRefresh().isRefreshing())
                    recyclerView.setRefreshing(false);

                switch (msg.what) {
                    case MSG.MSG_DETAILS_LIST_FOR_APP_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_DETAILS_LIST_FOR_APP_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
        realTimeListVOList = FastJsonUtil.getListBean(object.toString(), "body", "realTimeList", RealTimeListVO.class);
        if (page == 1) { // 刷新
            adapter.clear();
        }

        if (realTimeListVOList != null) {
            if (realTimeListVOList.size() < limit) {
                adapter.stopMore();
            }
        }

        adapter.addAll(realTimeListVOList);
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.data_detail_tv_pic_data, R.id.layout_real_time_price_tv_week, R.id.layout_real_time_price_tv_month, R.id.layout_real_time_price_tv_custom})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.data_detail_tv_pic_data:
                finish();
                break;
            case R.id.layout_real_time_price_tv_week:
                setWeekSelected();
                onRefresh();
                break;
            case R.id.layout_real_time_price_tv_month:
                setMonthSelected();
                onRefresh();
                break;
            case R.id.layout_real_time_price_tv_custom:
                setCustomSelected();
                pvStartTime.show();
                break;
        }
    }

    /**
     * 周选中状态
     */
    private void setWeekSelected() {
        type = "0";
        mStartDate = "";
        mEndDate = "";
        layoutRealTimePriceTvWeek.setBackgroundResource(R.color.app_color);
        layoutRealTimePriceTvWeek.setTextColor(getResources().getColor(R.color.colorWhite));
        layoutRealTimePriceTvMonth.setBackgroundResource(R.color.colorWhite);
        layoutRealTimePriceTvMonth.setTextColor(getResources().getColor(R.color.app_color));
        layoutRealTimePriceTvCustom.setBackgroundResource(R.color.colorWhite);
        layoutRealTimePriceTvCustom.setTextColor(getResources().getColor(R.color.app_color));
    }

    /**
     * 月 选中状态
     */
    private void setMonthSelected() {
        type = "1";
        mStartDate = "";
        mEndDate = "";
        layoutRealTimePriceTvWeek.setBackgroundResource(R.color.colorWhite);
        layoutRealTimePriceTvWeek.setTextColor(getResources().getColor(R.color.app_color));
        layoutRealTimePriceTvMonth.setBackgroundResource(R.color.app_color);
        layoutRealTimePriceTvMonth.setTextColor(getResources().getColor(R.color.colorWhite));
        layoutRealTimePriceTvCustom.setBackgroundResource(R.color.colorWhite);
        layoutRealTimePriceTvCustom.setTextColor(getResources().getColor(R.color.app_color));
    }

    /**
     * 自定义 选中状态
     */
    private void setCustomSelected() {
        type = "3";
        layoutRealTimePriceTvWeek.setBackgroundResource(R.color.colorWhite);
        layoutRealTimePriceTvWeek.setTextColor(getResources().getColor(R.color.app_color));
        layoutRealTimePriceTvMonth.setBackgroundResource(R.color.colorWhite);
        layoutRealTimePriceTvMonth.setTextColor(getResources().getColor(R.color.app_color));
        layoutRealTimePriceTvCustom.setBackgroundResource(R.color.app_color);
        layoutRealTimePriceTvCustom.setTextColor(getResources().getColor(R.color.colorWhite));
    }

    /**
     * 显示自定义开始时间选择
     */
    private void initStartTimePicker() {
        Calendar calendar = Calendar.getInstance();

        pvStartTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                mStartDate = DateUtil.DateToString(date, DateStyle.YYYY_MM_DD);
                pvEndTime.show();
            }
        })
                .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("下一步")//确认按钮文字
                .setContentSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("起始时间")//标题文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setCancelColor(Color.BLACK)
                .setSubmitColor(Color.BLACK)
                .setTextColorCenter(0xff37B5B4)
                .setRange(calendar.get(Calendar.YEAR) - 10, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
                .setDate(DateUtil.StringToDate(DateUtil.getCurrentDate(DateStyle.YYYY_MM_DD)))// 如果不设置的话，默认是系统时间*/
                .setLabel("年", "月", "日", "", "", "")
                .isDialog(false)//是否显示为对话框样式
                .build();
    }

    /**
     * 显示自定义结束时间选择
     */
    private void initEndTimePicker() {
        Calendar calendar = Calendar.getInstance();

        pvEndTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                mEndDate = DateUtil.DateToString(date, DateStyle.YYYY_MM_DD);
                onRefresh();
            }
        })
                .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("完成")//确认按钮文字
                .setContentSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("结束时间")//标题文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setCancelColor(Color.BLACK)
                .setSubmitColor(Color.BLACK)
                .setTextColorCenter(0xff37B5B4)
                .setRange(calendar.get(Calendar.YEAR) - 10, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
                .setDate(DateUtil.StringToDate(DateUtil.getCurrentDate(DateStyle.YYYY_MM_DD)))// 如果不设置的话，默认是系统时间*/
                .setLabel("年", "月", "日", "", "", "")
                .isDialog(false)//是否显示为对话框样式
                .build();
    }

    @Override
    public void onRefresh() {
        page = 1;
        BusinessRealTimePrice.priceDetailsForApp(this, priceId, mStartDate, mEndDate, type, standard, packing, storageMode, String.valueOf(page), String.valueOf(limit), mHandler);
    }

    @Override
    public void onLoadMore() {
            page++;
            BusinessRealTimePrice.priceDetailsForApp(this, priceId, mStartDate, mEndDate, type, standard, packing, storageMode, String.valueOf(page), String.valueOf(limit), mHandler);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (pvStartTime != null && pvStartTime.isShowing()) {
            pvStartTime.dismiss();
            return true;
        } else if (pvEndTime != null && pvEndTime.isShowing()) {
            pvEndTime.dismiss();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
